# dbplugs/quote.py
#
#

""" quote plugin """

__copyright__ = 'this file is in the public domain'

from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.plughelp import plughelp
from gozerbot.aliases import aliases
from gozerbot.db import db
import random, time

plughelp.add('quote', 'manage quotes')

class Quotes(object):

    """ quotes db interface """

    def size(self):
        """ return nr of quotes """
        result = db.execute(""" SELECT COUNT(*) FROM quotes """)
        return result[0][0]

    def add(self, nick, userhost, quote):
        """ add a quote """
        result = db.execute(""" INSERT INTO quotes(quote, userhost, \
createtime, nick) VALUES (%s, %s, %s, %s) """, (quote, userhost, \
time.time(), nick))
        return result

    def delete(self, quotenr):
        """ delete quote with id == nr """
        result = db.execute(""" DELETE FROM quotes WHERE indx = %s """, \
quotenr)
        return result

    def random(self):
        """ get random quote """
        result = db.execute(""" SELECT indx FROM quotes """)
        indices = []
        if not result:
            return
        for i in result:
            indices.append(i[0])
        if indices:
            idnr = random.choice(indices)
            return self.idquote(idnr)

    def idquote(self, quotenr):
        """ get quote by id """
        result = db.execute(""" SELECT indx, quote FROM quotes WHERE \
indx = %s """, quotenr)
        if result:
            return result[0]

    def whoquote(self, quotenr):
        """ get who quoted the quote """
        result = db.execute(""" SELECT nick, createtime FROM quotes WHERE \
indx = %s """, quotenr)
        if result:
            return result[0]

    def last(self):
        """ get last quote """
        result = db.execute(""" SELECT indx, quote FROM quotes ORDER BY \
indx DESC LIMIT 1 """)
        if result:
            return result[0]

    def search(self, what):
        """ search quotes """
        result = db.execute(""" SELECT indx, quote FROM quotes WHERE \
quote REGEXP %s """, what)
        if result:
            return result

    def searchlike(self, what):
        """ search quotes """
        result = db.execute(""" SELECT indx, quote FROM quotes WHERE \
quote LIKE %s """, what)
        if result:
            return result

quotes = Quotes()

def handle_quoteadd(bot, ievent):
    """ quote-add <txt> .. command that adds a quote """
    if not ievent.rest:
        ievent.missing("<txt>")
        return
    id = quotes.add(ievent.nick, ievent.userhost, ievent.rest)
    if id:
        ievent.reply('quote %s added' % id)
    else:
        ievent.reply('add quote failed')

cmnds.add('quote-add', handle_quoteadd, 'USER')
examples.add('quote-add', 'quote-add <txt> .. add quote', 'quote-add mekker')
aliases.data['aq'] = 'quote-add'

def handle_quotewho(bot, ievent):
    """ quote-who <nr> .. command that shows who added a quote """
    try:
        quotenr = int(ievent.args[0])
    except (IndexError, ValueError):
        ievent.missing("<nr>")
        return
    result = quotes.whoquote(quotenr)
    if not result[0] or not result[1]:
        ievent.reply('no who quote data available')
        return
    ievent.reply('quote #%s was made by %s on %s' % (quotenr, \
result[0], time.ctime(result[1])))

cmnds.add('quote-who', handle_quotewho, ['USER', 'WEB'])
examples.add('quote-who', 'quote-who <nr> .. show who quoted <quotenr>', \
'quote-who 1')
aliases.data['wq'] = 'quote-who'

def handle_quotedel(bot, ievent):
    """ quote-del <nr> .. delete quote by id """
    try:
        quotenr = int(ievent.args[0])
    except (IndexError, ValueError):
        ievent.missing('<nr>')
        return
    if quotes.delete(quotenr):
        ievent.reply('quote deleted')
    else:
        ievent.reply("can't delete quotenr %s" % quotenr)

cmnds.add('quote-del', handle_quotedel, ['QUOTE', 'OPER'])
examples.add('quote-del', 'quote-del <nr> .. delete quote with id <nr>', \
'quote-del 2')
aliases.data['dq'] = 'quote-del'

def handle_quotelast(bot, ievent):
    """ quote-last .. show last quote """
    quote = quotes.last()
    if quote != None:
        ievent.reply('#%s %s' % (quote[0], quote[1]))
    else:
        ievent.reply("can't fetch quote")

cmnds.add('quote-last', handle_quotelast, ['USER', 'WEB'])
examples.add('quote-last', 'show last quote', 'quote-last')
aliases.data['lq'] = 'quote-last'

def handle_quote2(bot, ievent):
    """ quote-2 .. show 2 random quotes """
    quote = quotes.random()
    if quote != None:
        ievent.reply('#%s %s' % (quote[0], quote[1]))
    quote = quotes.random()
    if quote != None:
        ievent.reply('#%s %s' % (quote[0], quote[1]))

cmnds.add('quote-2', handle_quote2, ['USER', 'WEB'])
examples.add('quote-2', 'show 2 quotes', 'quote-2')
aliases.data['2q'] = 'quote-2'

def handle_quoteid(bot, ievent):
    """ quote-id <nr> .. show quote by id """
    try:
        quotenr = int(ievent.args[0])
    except (IndexError, ValueError):
        ievent.missing('<nr>')
        return
    quote = quotes.idquote(quotenr)
    if quote != None:
        ievent.reply('#%s %s' % (quote[0], quote[1]))
    else:
        ievent.reply("can't fetch quotenr %s" % quotenr)

cmnds.add('quote-id', handle_quoteid, ['USER', 'WEB'])
examples.add('quote-id', 'quote-id <nr> .. get quote on id <nr> ', \
'quote-id 2')
aliases.data['iq'] = 'quote-id'

def handle_quote(bot, ievent):
    """ quote .. show random quote """
    quote = quotes.random()
    if quote != None:
        ievent.reply('#%s %s' % (quote[0], quote[1]))
    else:
        ievent.reply('no quotes yet')

cmnds.add('quote', handle_quote, ['USER', 'WEB'])
examples.add('quote', 'show random quote', 'quote')
aliases.data['q'] = 'quote'

def handle_quotesearch(bot, ievent):
    """ quote-searcg <txt> .. search quotes for <txt>"""
    if not ievent.rest:
        ievent.missing('<txt>')
        return
    else:
        what = ievent.rest
        nrtimes = 3
    try:
        result = quotes.search(what)
    except _mysql_exceptions.OperationalError:
        ievent.reply("can't make RE out of %s" % what)
        return
    if result:
        if nrtimes > len(result):
            nrtimes = len(result)
        randquotes = random.sample(result, nrtimes)
        for quote in randquotes:
            ievent.reply("#%s %s" % (quote[0], quote[1]))
    else:
        ievent.reply('no quotes found with %s' % what)

cmnds.add('quote-search', handle_quotesearch, ['USER', 'WEB'])
examples.add('quote-searcg', 'quote-search <txt> .. search quotes for <txt>', \
'quote-search bla')
aliases.data['sq'] = 'quote-search'

def handle_quotescount(bot, ievent):
    """ quote-count .. show number of quotes """
    ievent.reply('quotes count is %s' % quotes.size())

cmnds.add('quote-count', handle_quotescount, ['USER', 'WEB'])
examples.add('quote-count', 'count nr of quotes', 'quote-count')
aliases.data['cq'] = 'quote-count'
